package org.example.controller;

import org.example.entity.User;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/users")
public class UserController {

    // 模拟数据库
    static Map<Long, User> users = new HashMap<Long,User>();

    @GetMapping("/{userId}")
    public String getUserById(@PathVariable Long userId) {
        System.out.println("收到了get请求" + userId);
        User user = users.get(userId);

        if (user != null) return user.toString();

        return "未查到用户";
    }


    @PostMapping
    public String addUser(@RequestBody User user) {
        System.out.println("收到了post请求" + user);
        users.put(user.getId(), user);
        return "添加用户成功";
    }

    @GetMapping
    public List<User> getUserList() {
        System.out.println("收到了getList请求");
        Collection<User> values = users.values();
        return values.stream().toList();
    }

    @PutMapping("{userId}")
    public String putUser(@PathVariable Long userId, @RequestBody User user) {
        System.out.println("收到了post请求");

        User user1 = users.get(userId);
        if (user1 == null) return "用户不存在";

        users.put(userId, user);
        return "已更新数据";
    }

    @DeleteMapping("{userId}")
    public String deleteUser(@PathVariable Long userId) {
        System.out.println("收到了delete请求");
        User user = users.get(userId);
        if (user == null) return "用户不存在";

        users.remove(userId);
        return "删除用户成功";
    }

}